const util = {
  trim: str => {
    return str.replace(/(^\s*)|(\s*$)/g, '');
  },
  hasRole: {
    SUPERVISOR: () => {
      if (util.getCookie('userInfo')) {
        const userInfo = JSON.parse(util.getCookie('userInfo'));
        if (userInfo.role === 'ADMIN' || userInfo.role === 'SUPERVISOR') {
          return true;
        }
      }
      return false;
    },
  },
  delCookie: name => {
    const exp = new Date();
    exp.setTime(exp.getTime() - 1);
    const cval = util.getCookie(name);
    if (cval != null) {
      document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString();
    }
  },
  setCookie: (key, value, day) => {
    const now = new Date();
    const expiresTime = new Date(now.getTime() + day * 12 * 60 * 60 * 1000);
    document.cookie = key + '=' + encodeURIComponent(value) + ';expires=' + expiresTime;
  },
  getCookie: key => {
    if (document.cookie) {
      const cookieList = document.cookie.split(';');
      let arr = null;
      for (let i = 0; i < cookieList.length; i++) {
        if (cookieList[i].indexOf('=') > 0) {
          arr = cookieList[i].split('=');
          if (util.trim(arr[0]) === key) {
            return decodeURIComponent(arr[1]);
          }
        }
      }
    }
    return '';
  },
  getUserBasic (that) {
    return new Promise((res, rej) => {
      that.$apollo
        .query({
          query: that.$graphqls.user.user,
          variables: {
            id: '-',
          },
          fetchPolicy: 'network-only',
        })
        .then(v => {
          if (!v.data.user || v.data.user === 'null') {
            that.$router.push({ name: 'login' });
            return;
          }
          that.$store.state.user = v.data.user;
          res(v);
        })
        .catch(err => {
          if (err) {
            rej(err);
          }
        });
    });
  },
};

export default util;
